package com.example.gfsquadwebviewproject.presenter.service.mqtt;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;

import com.example.gfsquadwebviewproject.data.ConfigData;
import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.presenter.update.UpdateAppClassHolder;
import com.example.gfsquadwebviewproject.service.MyMqttService;
import com.example.gfsquadwebviewproject.util.L;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;

public class MqttServiceClass implements IMqttService{
    private String TAG = "MqttServiceClass";

    Context context;
    ConfigData configData;

    private MyMqttService.mBinder binder;

    UpdateAppClassHolder updateAppClassHolder;
    IMqttCallbcak iMqttCallbcak;

    Handler handler;

    public MqttServiceClass(Context context,IMqttCallbcak iMqttCallbcak) {
        this.context = context;
        this.iMqttCallbcak = iMqttCallbcak;
        configData = new ConfigData(context);
        handler = new Handler();
    }

    public void toStartService(){
        Intent intent = new Intent(context, MyMqttService.class);
        // 传入服务的Intent，和已经定义好的ServiceConnection对象，BIND_AUTO_CREATE为标志，表示活动和服务绑定后自动创建一个服务的实例
        context.bindService(intent, connection, context.BIND_AUTO_CREATE);
    }

    //启动socket服务
    @Override
    public void startService() {
        try {
            toStartService();
        }
        catch (Exception e ){
            L.d(TAG,"startService error:"+e);
        }
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        // 活动和服务的绑定失去的时候自动调用，比如服务被杀死或者报错，
        // 这时候ServiceConnection会保持激活，在活动下次启动时会收到一个通知
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        // 活动和服务绑定的时候自动调用，即bindService()函数调用时
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyMqttService.mBinder) service; // 通过Service向下转型得到一个MyService.mBinder的对象
            connect();
        }
    };


    /**
     * 连接Mqtt服务器
     */
    @Override
    public void connect() {
        binder.connect(iEasyMqttCallBack);
    }

    @Override
    public void disconnect() {
        binder.disconnect();
    }

    @Override
    public void reConnect() {
        binder.reConnect(iEasyMqttCallBack);
    }

    //重新连接
    private void reconnection(int delaySecond){
        if (handler!=null){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (binder!=null){
                        if (!binder.isConnected()){
                            binder.connect(iEasyMqttCallBack);
                        }
                    }
                }
            },delaySecond * 1000);
        }
    }

    //mqtt Service的回调
    IEasyMqttCallBack iEasyMqttCallBack = new IEasyMqttCallBack() {
        @Override
        public void messageArrived(String topic, String message, int qos) {
            L.d(TAG, "收到消息 message = " + message+'\n' +"主题--> " + topic);
            try{
                String msgType = topic.split("/")[1];

                //版本更新
                if (msgType.equals("version")){
                    if (updateAppClassHolder==null) {
                        updateAppClassHolder = UpdateAppClassHolder.instance(context);
                    }
                    if (!updateAppClassHolder.getIsBusy()) {
                        updateAppClassHolder.compareVersions();
                    }
                }

            }
            catch (Exception e){
                L.d(TAG,"messageArrived error："+e);
            }
        }

        @Override
        public void connectionLost(Throwable arg0) {
            chanceMqttStatus();
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            L.d(TAG, "deliveryComplete 发送完毕:" + arg0.toString());
        }
        @Override
        public void connectSuccess(IMqttToken arg0) {
            chanceMqttStatus();
            subscribe();
        }
        @Override
        public void connectFailed(IMqttToken arg0, Throwable arg1) {
            //连接失败
            chanceMqttStatus();
        }
    };


    //连接状态变更
    private void chanceMqttStatus(){
        if (binder!=null) {
            Constant.isMqttConnect = binder.isConnected();
            L.d(TAG, "连接状态:" + Constant.isMqttConnect);
            if (context!=null) {
                context.sendBroadcast(new Intent(Constant.ACTION_MQTT_CONNECT_STATUS));
            }
            if (!Constant.isMqttConnect) {
                reconnection(30);
            }
        }
    }


    /**
     * 订阅主题
     */
    private void subscribe() {
        String sub;
        if (configData.getClassId()!=null && !configData.getClassId().equals("null")){
            sub = configData.getClassId()+"/#";
        }
        else {
            sub = "#";
        }

        L.d(TAG,"订阅号："+sub);
        String[] topics = new String[]{sub};
        //主题对应的推送策略 分别是0, 1, 2 建议服务端和客户端配置的主题一致
        // 0 表示只会发送一次推送消息 收到不收到都不关心
        // 1 保证能收到消息，但不一定只收到一条
        // 2 保证收到切只能收到一条消息
        int[] qoss = new int[]{2};
        binder.subscribe(topics, qoss);
    }

    @Override
    public void stopService() {
        try {
            if (binder != null) {
                binder.stop();
                binder = null;
            }

            if (connection != null) {
                context.unbindService(connection);
            }

            if (handler != null){
                handler.removeCallbacksAndMessages(null);
                handler = null;
            }

        }
        catch (Exception e){
            L.d(TAG, "stopService error:"+e);
        }
    }

}
